package com.wencun.cunpicturebackend.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wencun.cunpicturebackend.annotation.AuthCheck;
import com.wencun.cunpicturebackend.common.BaseResponse;
import com.wencun.cunpicturebackend.common.DeleteRequest;
import com.wencun.cunpicturebackend.common.ResultUtils;
import com.wencun.cunpicturebackend.constant.UserConstant;
import com.wencun.cunpicturebackend.enums.SpaceLevelEnum;
import com.wencun.cunpicturebackend.exception.BusinessException;
import com.wencun.cunpicturebackend.exception.ErrorCode;
import com.wencun.cunpicturebackend.exception.ThrowUtils;
import com.wencun.cunpicturebackend.model.dto.picture.PictureQueryRequest;
import com.wencun.cunpicturebackend.model.dto.space.*;
import com.wencun.cunpicturebackend.model.entity.Picture;
import com.wencun.cunpicturebackend.model.entity.Space;
import com.wencun.cunpicturebackend.model.entity.User;
import com.wencun.cunpicturebackend.model.vo.SpaceVO;
import com.wencun.cunpicturebackend.service.SpaceService;
import com.wencun.cunpicturebackend.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @program: cun-picture-backend
 * @ClassName SpaceController
 * @author: wencun
 * @create: 2025-09-08 15:32
 * @Version 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/space")
public class SpaceController {

    private final SpaceService spaceService;
    private final UserService userService;

    public SpaceController(SpaceService spaceService, UserService userService) {
        this.spaceService = spaceService;
        this.userService = userService;
    }
    /**
     * 添加空间
     * @param spaceAddRequest
     * @param request
     * @return BaseResponse<Long>
     * @time 2025-09-08 20:28
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long newId = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(newId);
    }

    /**
     * 根据id获取空间信息（仅管理员可用）
     *
     * @param id
     * @param request
     * @return BaseResponse<Space>
     * @time 2025-09-08 17:35
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(space);
    }

    /**
     * 根据id获取空间信息（脱敏）
     *
     * @param id
     * @param request
     * @return BaseResponse<SpaceVO>
     * @time 2025-09-08 19:56
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        return ResultUtils.success(spaceVO);
    }


    /**
     * 分页获取空间列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }

    /**
     * 获取空间分页列表（脱敏）
     * @param spaceQueryRequest
     * @return BaseResponse<Page<Space>>
     * @time 2025-09-08 20:08
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpacePage(@RequestBody SpaceQueryRequest spaceQueryRequest, HttpServletRequest request) {
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage));
    }


    /**
     * 获取空间等级列表
     * @return BaseResponse<List<SpaceLevel>>
     * @time 2025-09-08 20:08
     */
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        SpaceLevelEnum[] spaceLevelArr = SpaceLevelEnum.values();
        List<SpaceLevel> levelList = Arrays.stream(spaceLevelArr)
                .map(spaceLevelEnum ->
                        new SpaceLevel(spaceLevelEnum.getValue(), spaceLevelEnum.getText(), spaceLevelEnum.getMaxCount(), spaceLevelEnum.getMaxSize())
                ).collect(Collectors.toList());
        return ResultUtils.success(levelList);
    }


    /**
     * 删除空间
     * @param deleteRequest
     * @param request
     * @return BaseResponse<Boolean>
     * @time 2025-09-08 20:14
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> delete(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        Long spaceId = deleteRequest.getId();
        if (spaceId == null || spaceId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断空间是否存在
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(ObjUtil.isNull(space), ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        User loginUser = userService.getLoginUser(request);
        // 仅本人或管理员可删除
        spaceService.checkSpaceAuth(loginUser, space);
        // 执行删除
        boolean removed = spaceService.removeById(spaceId);
        ThrowUtils.throwIf(!removed, ErrorCode.OPERATION_ERROR, "删除空间失败");
        return ResultUtils.success(true);
    }

    /**
     * 更新空间（仅管理员可用）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space, false);
        // 判断是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 编辑空间（给用户可用）
     * @param spaceEditRequest
     * @param request
     * @return BaseResponse<Boolean>
     * @time 2025-09-08 20:16
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 设置编辑时间
        space.setEditTime(new Date());
        // 数据校验
        spaceService.validSpace(space, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        spaceService.checkSpaceAuth(loginUser, oldSpace);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }




}